import fs from 'node:fs';
import path from 'node:path';
import { errorDialog } from '@e/dialog';

/**
 * 检查路径，若路径存在则在路径后面加序号，直到不存在为止
 */
export function addNumber(basePath: string, type: 'file' | 'dir', format = '$', max = 999) {
	let root = '',
		ext = '',
		p: string,
		count = 1;

	if (type === 'file') {
		const arr = basePath.match(/(.+)\.([a-zA-Z0-9]+)$/);

		if (arr) {
			root = arr[1];
			ext = arr[2];
		} else {
			return errorDialog('错误', `路径格式错误："${basePath}"`);
		}
	} else {
		root = basePath;
	}

	p = root + format.replace('$', '');

	if (type === 'file') p += '.' + ext;

	if (!fs.existsSync(p)) return p;

	while (true) {
		p = root + format.replace('$', `(${count++})`);

		if (type === 'file') p += '.' + ext;

		if (!fs.existsSync(p)) return p;

		if (count > max) return;
	}
}

/**
 * 检查路径，返回文件名
 */
export function addNumberFilename(
	basePath: string,
	filename: string,
	type: 'file' | 'dir',
	format?: string,
	max?: number
) {
	const filePath = path.join(basePath, filename);

	const _path = addNumber(filePath, type, format, max);

	if (_path) {
		return path.basename(_path);
	}
}
